package cc.magicjson.data.operation.router.db.config;

import cc.magicjson.data.operation.router.db.executor.EntityOperationExecutor;
import cc.magicjson.data.operation.router.db.router.OperationRouter;
import cc.magicjson.data.operation.router.db.service.DataOperationService;
import cc.magicjson.data.operation.router.db.service.impl.DefaultDataOperationService;
import cc.magicjson.data.operation.router.db.datasource.DataSourceHolder;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DataOperationConfig {

    @Value("${db.slave.write.enabled:false}")
    private boolean enableSlaveWrite;
    @Autowired
    private ApplicationContext applicationContext;
    @Bean
    public OperationRouter operationRouter(
            @Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("slaveDataSource") DataSource slaveDataSource) {
        DataSourceHolder.setMaster(masterDataSource);
        DataSourceHolder.setSlave(slaveDataSource);
        return new OperationRouter(enableSlaveWrite);
    }

    @Bean
    public DataOperationService dataOperationService(
            OperationRouter router,
            EntityOperationExecutor executor) {
        return new DefaultDataOperationService(router, executor, applicationContext);
    }
}
